//
//  UITabBar+badge.m
//  Fruit
//
//  Created by X1aoHey on 15/12/9.
//  Copyright © 2015年 kai xie. All rights reserved.
//

#import "UITabBar+badge.h"

#define TabbarItemNums 5.0    //tabbar的数量

@implementation UITabBar (badge)

//显示小红点
- (void)showBadgeOnItemIndex:(int)index Value:(NSString *)value
{
    //移除之前的小红点
    [self removeBadgeOnItemIndex:index];
    
    //新建小红点
    UILabel *badgeView = [[UILabel alloc] init];
    badgeView.tag = 888 + index;
    badgeView.layer.cornerRadius = 7.5;
    badgeView.layer.borderColor = Color(111, 185, 112).CGColor;
    badgeView.layer.borderWidth = 1.0f;
    badgeView.backgroundColor = [UIColor whiteColor];
    badgeView.font = [UIFont systemFontOfSize:9];
    badgeView.text = value;
    badgeView.textColor = Color(111, 185, 112);
    badgeView.textAlignment = NSTextAlignmentCenter;
    badgeView.layer.masksToBounds = YES;
    CGRect tabFrame = self.frame;
    
    CGSize size = CGSizeMake(20, 15);
    //计算实际frame大小，并将label的frame变成实际大小
    CGSize titleSize = [value boundingRectWithSize:size
                                                      options:NSStringDrawingUsesLineFragmentOrigin
                                                   attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:12]}
                                                      context:nil].size;
    
    //确定小红点的位置
    float percentX = (index + 0.58) / TabbarItemNums;
    CGFloat x = ceilf(percentX * tabFrame.size.width);
    CGFloat y = ceilf(0.1 * tabFrame.size.height);
    if (titleSize.width <= 15) {
        badgeView.frame = CGRectMake(x, y, 15, 15);
    }
    else {
        badgeView.frame = CGRectMake(x, y, titleSize.width+10, 15);
        badgeView.layer.cornerRadius = 7.5;
    }
    [self addSubview:badgeView];
}

//隐藏小红点
- (void)hideBadgeOnItemIndex:(int)index
{
    //移除小红点
    [self removeBadgeOnItemIndex:index];
}

- (void)removeBadgeOnItemIndex:(int)index
{
    //按照tag值进行移除
    for (UIView *subView in self.subviews) {
        if (subView.tag == 888 + index) {
            [subView removeFromSuperview];
        }
    }
}
@end
